package com.cnunicom.modules.mp.controller;

import com.alibaba.fastjson.JSON;
import com.cnunicom.common.utils.Constant;
import com.cnunicom.common.utils.R;
import com.cnunicom.common.websocket.WebSocketServer;
import com.cnunicom.modules.mp.service.WxMpUserService;
import com.cnunicom.modules.tra.entity.MemberEntity;
import com.cnunicom.modules.tra.service.MemberService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.commons.logging.Log;
import org.slf4j.Logger;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.builders.LoginEndpointBuilder;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Map;

/**
 * @Author: dingziyuan
 * @Date: 2020/2/17/017 9:24
 * @Description: 会员注册调用的公众号接口
 */
@RestController
@RequestMapping("mp/user")
public class MpUserController {

    @Resource
    private WxMpService wxMpService;
    @Resource
    private WxMpUserService wxMpUserService;
    @Resource
    private MemberService memberService;

    /**
     * 注册：会员跳转注册页面时调用服务号公众号接口，将地址返回给前端
     *
     * @return
     */
    @GetMapping("/getOauth2URL")
    @ResponseBody
    public String oauth2URL(@RequestParam Map<String, Object> params) {

        wxMpService.switchover(Constant.mpMessage.SERVING_APP_ID.getValue());

        String superiorType = (String) params.get("superiorType");
        String superiorId = (String) params.get("superiorId");

        String redirectURI = null;
        // 上级为宾馆员工
        if ("1".equals(superiorType)) {
            redirectURI = Constant.mpMessage.STAFF_REDIRECT_URI.getValue() + superiorId;
        }
        // 上级为各机关单位
        if ("0".equals(superiorType)) {
            redirectURI = Constant.mpMessage.UNIT_REDIRECT_URI.getValue() + superiorId;
        }
        return wxMpService.oauth2buildAuthorizationUrl(redirectURI, "snsapi_userinfo", "STATE");
    }

    /**
     * 注册：授权链接的回调接口
     */
    @GetMapping("/matchUser/{code}")
    @ResponseBody
    public R matchUser(@PathVariable String code) throws WxErrorException {
        wxMpService.switchover(Constant.mpMessage.SERVING_APP_ID.getValue());
        WxMpOAuth2AccessToken token = wxMpService.oauth2getAccessToken(code);
        WxMpUser user = wxMpService.oauth2getUserInfo(token, "zh_CN");
        Integer count = wxMpUserService.query().eq("union_id", user.getUnionId())
                .eq("subscribe", "1").count();
        if (count > 0) {
            return R.ok().put("unionId", user.getUnionId());
        }
        return R.error("您未关注运城宾馆订阅号，请关注后再进行注册");
    }

    /**
     * 核验：扫描核对二维码后拼接回调地址
     */
    @GetMapping("/check/splice/{userId}")
    @ResponseBody
    public String splice(@PathVariable String userId) {
        wxMpService.switchover(Constant.mpMessage.SERVING_APP_ID.getValue());
        return wxMpService.oauth2buildAuthorizationUrl(Constant.mpMessage.CHECK_REDIRECT_URI
                        .getValue() + "?userId=" + userId,"snsapi_userinfo", "STATE");

    }

    /**
     * 核验：核对二维码校验接口
     */
    @GetMapping("/check/{userId}/{code}")
    public R check(@PathVariable String code,@PathVariable String userId) throws WxErrorException, IOException {

        wxMpService.switchover(Constant.mpMessage.SERVING_APP_ID.getValue());
        WxMpOAuth2AccessToken token = wxMpService.oauth2getAccessToken(code);
        WxMpUser user = wxMpService.oauth2getUserInfo(token, "zh_CN");

        Integer count = wxMpUserService.query().eq("union_id", user.getUnionId())
                .eq("subscribe", "1").count();
        Integer mebCount = memberService.query().eq("union_id", user.getUnionId()).count();

        if (count == 0) {
            return R.error("您未关注运城宾馆订阅号，请先关注订阅号！");
        }

        if (mebCount == 0) {
            return R.error("您还未注册成为会员！");
        }
        // 数据返回
        if (count > 0) {
            MemberEntity member = memberService.query().eq("union_id", user.getUnionId()).one();
            WebSocketServer.sendInfo(JSON.toJSONString(member),userId);
            return R.ok("吧台已认证您是会员，开始办理手续，请稍等。");
        }

        return R.error();
    }
}

